package org.system.core.controller.system;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.system.core.annotation.Log;
import org.system.core.common.PageResult;
import org.system.core.common.Result;
import org.system.core.domain.entity.SysDept;
import org.system.core.domain.entity.SysRole;
import org.system.core.domain.entity.SysUser;
import org.system.core.domain.entity.SysUserRole;
import org.system.core.domain.model.LoginUser;
import org.system.core.enums.BusinessType;
import org.system.core.service.system.*;
import org.system.core.utils.PageUtils;
import org.system.core.utils.SecurityUtils;
import org.system.core.utils.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author baoRoot
 */
@RestController
@RequestMapping("/system/role")
@Api(tags={"角色模块"})
public class SysRoleController {

    private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysDeptService sysDeptService;

    @GetMapping("/list")
    @ApiOperation("获取角色列表")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    public PageResult<SysRole> list(SysRole sysRole) {
        logger.info("获取角色列表: {}", sysRole);
        PageUtils.startPage();
        List<SysRole> list = sysRoleService.selectRoleList(sysRole);
//        if (!list.isEmpty()) {
//            list = list.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList());
//        }
        PageInfo<SysRole> pageInfo = new PageInfo<>(list);
        return PageResult.ok(pageInfo);
    }

    @GetMapping("/{roleId}")
    @ApiOperation("根据角色id或者角色详细信息")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    public Result<SysRole> getRoleInfo(@PathVariable Long roleId) {
        logger.info("根据角色id或者角色详细信息：{}", roleId);
        return Result.ok(sysRoleService.selectRoleById(roleId));
    }

    @PostMapping
    @ApiOperation("新增角色")
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    public Result<SysRole> createRole(@Validated @RequestBody SysRole sysRole) {
        logger.info("新增角色： {}", sysRole);
        sysRoleService.createRole(sysRole);
        return Result.ok();
    }

    @PutMapping
    @ApiOperation("修改角色")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    public Result<String> updateRole(@Validated @RequestBody SysRole sysRole) {
        logger.info("修改角色： {}", sysRole);
        sysRoleService.checkRoleAllowed(sysRole);
        sysRoleService.checkRoleDataScope(sysRole.getRoleId());
        sysRoleService.checkUserUnique(sysRole);
        sysRoleService.updateRole(sysRole);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser) && !loginUser.getUser().isAdmin()) {
            loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
            loginUser.setUser(sysUserService.selectUserByUserName(loginUser.getUser().getUserName()));
            tokenService.setLoginUser(loginUser);
        }
        return Result.ok();
    }

    @PutMapping("/dataScope")
    @ApiOperation("修改角色数据权限")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    public Result<String> dataScope(@RequestBody SysRole sysRole) {
        logger.info("修改角色数据权限： {}", sysRole);
        sysRoleService.authDataScope(sysRole);
        return Result.ok();
    }

    @PutMapping("/status")
    @ApiOperation("修改角色状态")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    public Result<String> changeStatus(@RequestBody SysRole sysRole) {
        logger.info("修改角色状态： {}", sysRole);
        sysRoleService.updateRoleStatus(sysRole);
        return Result.ok();
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/{roleIds}")
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    public Result<String> deleteRole(@PathVariable Long[] roleIds) {
        logger.info("删除角色： {}", roleIds);
        sysRoleService.deleteRoleByIds(roleIds);
        return Result.ok();
    }

    @ApiOperation("取消授权用户")
    @PutMapping("/authUser/cancel")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    public Result<String> cancelAuthUser(@RequestBody SysUserRole userRole){
        logger.info("取消授权用户： {}", userRole);
        sysRoleService.deleteAuthUser(userRole);
        return Result.ok();
    }

    @ApiOperation("获取已分配用户角色列表")
    @GetMapping("/authUser/allocatedList")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    public PageResult<SysUser> allocatedList(SysUser sysUser) {
        logger.info("获取已分配用户角色列表: {}", sysUser);
        PageUtils.startPage();
        List<SysUser> list = sysUserService.selectAllocatedList(sysUser);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return PageResult.ok(pageInfo);
    }

    @ApiOperation("获取未分配用户角色列表")
    @GetMapping("/authUser/unallocatedList")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    public PageResult<SysUser> unallocatedList(SysUser sysUser) {
        logger.info("获取未分配用户角色列表: {}", sysUser);
        PageUtils.startPage();
        List<SysUser> list = sysUserService.selectUnallocatedList(sysUser);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return PageResult.ok(pageInfo);
    }

    @ApiOperation("批量取消授权用户")
    @PutMapping("/authUser/cancelAll")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    public Result<String> cancelAuthUserAll(Long roleId, Long[] userIds){
        logger.info("批量取消授权用户: 角色： {}, 用户id：{}", roleId, userIds);
        sysRoleService.deleteAuthUsers(roleId, userIds);
        return Result.ok();
    }

    @ApiOperation("批量选择用户授权")
    @PutMapping("/authUser/selectAll")
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    public Result<SysRole> selectAuthUserAll(Long roleId, Long[] userIds) {
        logger.info("批量选择用户授权: 角色： {}, 用户id：{}", roleId, userIds);
        sysRoleService.insertAuthUsers(roleId, userIds);
        return Result.ok();
    }

    @ApiOperation("获取对应角色部门树列表")
    @GetMapping(value = "/deptTree/{roleId}")
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    public Result<Map<String, Object>> deptTree(@PathVariable("roleId") Long roleId) {
        Map<String, Object> map = new HashMap<>();
        map.put("checkedKeys", sysDeptService.selectDeptListByRoleId(roleId));
        map.put("deptList", sysDeptService.selectDeptTreeList(new SysDept()));
        return Result.ok(map);
    }

}
